package com.finance.action.admin.recharge;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.common.vo.JsonVo;
import com.finance.entity.Balance;
import com.finance.entity.BalanceRecord;
import com.finance.entity.User;
import com.finance.service.BalanceRecordService;
import com.finance.service.BalanceService;
import com.finance.service.UserService;
import com.web.utils.UserManagerUtil;

@Controller("baBalanceAction")
@RequestMapping("admin/balan")
public class BalanceAction {
	@Resource(name = "UserService")
	private UserService userService;
	
	@Resource(name = "BalanceService")
	private BalanceService balanceService;
	
	@Resource(name = "BalanceRecordService")
	private BalanceRecordService balanceRecordService;
	
	@RequestMapping("balan.htm")
	public String balan(ModelMap model){
		List<User> list = userService.findByJurisdiction(3);
		model.addAttribute("list", list);
		return "manage/recharge/recharge";
	}
	
	
	@ResponseBody
	@RequestMapping("balan_ajax")
	public JsonVo<String> balan_ajax(Balance balance){
		JsonVo<String> json = new JsonVo<String>();
		User user = UserManagerUtil.getCurrentUser();
		if (user == null) {
			json.setCode(1);
			json.setMsg("当前登陆账户为空，充值失败");
			json.setSuccess(false);
			return json;
		}
		if (user.getJurisdiction() != 1 && user.getJurisdiction() != 2) {
			json.setCode(1);
			json.setMsg("当前登陆账户没有充值权限，充值失败");
			json.setSuccess(false);
			return json;
		}
		
		Balance balance2 = balanceService.selectByPrimaryKey(balance.getUserId());
		if (balance2 == null) {
			balanceService.insert(balance);
			
			BalanceRecord balanceRecord = new BalanceRecord();
			balanceRecord.setUserId(balance.getUserId());
			balanceRecord.setRdTime(new Date());
			balanceRecord.setRdType(1);
			balanceRecord.setRdComment("充值");
			balanceRecord.setRdValue(balance.getBalanceCount());
			balanceRecordService.insert(balanceRecord);
			json.setCode(200);
			json.setMsg("充值成功");
			json.setSuccess(true);
		}else {
			Long mo = balance2.getBalanceCount() + balance.getBalanceCount();
			balance2.setBalanceCount(mo);
			balanceService.updateByPrimaryKeySelective(balance2);
			
			BalanceRecord balanceRecord = new BalanceRecord();
			balanceRecord.setUserId(balance.getUserId());
			balanceRecord.setRdTime(new Date());
			balanceRecord.setRdType(1);
			balanceRecord.setRdComment("充值");
			balanceRecord.setRdValue(balance.getBalanceCount());
			balanceRecordService.insert(balanceRecord);
			json.setCode(200);
			json.setMsg("充值成功");
			json.setSuccess(true);
		}
		
		return json;
	}

}
